// #include "thread.hpp"
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <iostream>
#include <string>
#include <cstring>
#include <thread>

void* getInfo(std::string server_ip, uint16_t server_port, int sockfd)
{
    while (true)
    {
        char buf[1024];
        struct sockaddr_in ans;
        socklen_t len = sizeof(ans);

        int back_ret = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr*)&ans, &len);
        if (back_ret > 0)
        {
            buf[back_ret] = '\0';
            std::cerr << buf << std::endl;
        }
        // std::cerr << "back_ret:" << back_ret << std::endl;
    }

    return nullptr;
}

void* sendInfo(std::string server_ip, uint16_t server_port, int sockfd)
{
    struct sockaddr_in server;
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());      // 字符串转网络二进制
    
    while (true)
    {
        std::string message;
        std::cout << "输入消息:";
        std::cin >> message;

        int send_ret = sendto(sockfd, message.c_str(), message.size(), 0, (struct sockaddr*)&server, sizeof(server));
        
        if (message == "QUIT")
        {
            return nullptr;
        }
    }

    return nullptr;
}

int main(int argc, char* args[])
{
    if (argc != 3)
    {
        std::cerr << "格式错误，正确格式: ./UdpClient ip port";
        return 1;
    }

    std::string server_ip = args[1];
    uint16_t server_port = std::stoi(args[2]);

    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cerr << "socket failure" << std::endl;
        return 1;
    }

    std::thread t1(sendInfo, server_ip, server_port, sockfd);
    std::thread t2(getInfo, server_ip, server_port, sockfd);
    
    t1.join();
    t2.join();

    return 0;
}